/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.solr.request;

import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.util.RefCounted;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.core.SolrCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;

/**
 * Base implementation of <code>SolrQueryRequest</code> that provides some
 * convenience methods for accessing parameters, and manages an IndexSearcher
 * reference.
 *
 * <p>
 * The <code>close()</code> method must be called on any instance of this
 * class once it is no longer in use.
 * </p>
 *
 *
 * @version $Id: SolrQueryRequestBase.java 1065312 2011-01-30 16:08:25Z rmuir $
 */
public abstract class SolrQueryRequestBase implements SolrQueryRequest {
	  public static Logger log = LoggerFactory.getLogger(SolrQueryRequestBase.class);

  /**
   * @deprecated Use org.apache.solr.common.params.CommonParams
   */
  @Deprecated
  public static final String QUERY_NAME="q";
  /**
   * @deprecated Use org.apache.solr.common.params.CommonParams
   */
  @Deprecated
  public static final String START_NAME="start";
  /**
   * @deprecated Use org.apache.solr.common.params.CommonParams
   */
  @Deprecated
  public static final String ROWS_NAME="rows";
  /**
   * @deprecated Use org.apache.solr.common.params.CommonParams
   */
  @Deprecated
  public static final String XSL_NAME="xsl";
  /**
   * @deprecated Use org.apache.solr.common.params.CommonParams
   */
  @Deprecated
  public static final String QUERYTYPE_NAME="qt";

  protected final SolrCore core;
  protected final SolrParams origParams;
  protected SolrParams params;
  protected Map<Object,Object> context;
  protected Iterable<ContentStream> streams;

  public SolrQueryRequestBase(SolrCore core, SolrParams params) {
    this.core = core;
    this.params = this.origParams = params;
  }

  public Map<Object,Object> getContext() {
    // SolrQueryRequest as a whole isn't thread safe, and this isn't either.
    if (context==null) context = new HashMap<Object,Object>();
    return context;
  }

  public SolrParams getParams() {
    return params;
  }

  public SolrParams getOriginalParams() {
    return origParams;
  }

  public void setParams(SolrParams params) {
    this.params = params;
  }

  /**
   * @deprecated Use {@link #getParams()} instead.
   */
  @Deprecated
  public String getParam(String name) {
    return params.get(name);
  }

  /**
   * @deprecated Use {@link #getParams()} instead.
   */
  @Deprecated
  public String[] getParams(String name) {
    return params.getParams(name);
  }

  /**
   * @deprecated use getParams().required().getInt( name ) instead
   */
  @Deprecated
  public int getIntParam(String name) {
    String s = getParam(name);
    if (s==null) {
      throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"Missing required parameter '"+name+"' from " + this);
    }
    return Integer.parseInt(s);
  }

  /**
   * @deprecated use getParams().required().getInt( name ) instead
   */
  @Deprecated
  public int getIntParam(String name, int defval) {
    String s = getParam(name);
    return s==null ? defval : Integer.parseInt(s);
  }

  /**
   * @deprecated use getParams().required().getParam( name ) instead
   */
  @Deprecated
  public String getStrParam(String name) {
    String s = getParam(name);
    if (s==null) {
      throw new SolrException( SolrException.ErrorCode.SERVER_ERROR,"Missing required parameter '"+name+"' from " + this);
    }
    return s;
  }

  /**
   * @deprecated use getParams().required().getParam( name ) instead
   */
  @Deprecated
  public String getStrParam(String name, String defval) {
    String s = getParam(name);
    return s==null ? defval : s;
  }

  /**
   * @deprecated Use {@link #getParams()} and {@link CommonParams#Q} instead.
   */
  @Deprecated
  public String getQueryString() {
    return params.get(CommonParams.Q);
  }

  /**
   * @deprecated Use {@link #getParams()} and {@link CommonParams#QT} instead.
   */
  @Deprecated
  public String getQueryType() {
    return params.get(CommonParams.QT);
  }

  /**
   * starting position in matches to return to client
   * @deprecated Use {@link #getParams()} and {@link CommonParams#START} instead.
   */
  @Deprecated
  public int getStart() {
    return params.getInt(CommonParams.START, 0);
  }

  /**
   * number of matching documents to return
   * @deprecated Use {@link #getParams()} and {@link CommonParams#ROWS} instead.
   */
  @Deprecated
  public int getLimit() {
    return params.getInt(CommonParams.ROWS, 10);
  }


  protected final long startTime=System.currentTimeMillis();
  // Get the start time of this request in milliseconds
  public long getStartTime() {
    return startTime;
  }

  // The index searcher associated with this request
  protected RefCounted<SolrIndexSearcher> searcherHolder;
  
  public SolrIndexSearcher getSearcher() {
    if(core == null) return null;//a request for a core admin will no have a core
    // should this reach out and get a searcher from the core singleton, or
    // should the core populate one in a factory method to create requests?
    // or there could be a setSearcher() method that Solr calls

    String partion=this.getParams().get(CommonParams.PARTION,"default");
    boolean higohb=this.getParams().getBool(CommonParams.HIGOHB,false);
    if(partion!=null&&!partion.trim().isEmpty())
    {
    	this.decref();
    	searcherHolder= core.getSearcher(partion,false,false,higohb);
    	if(searcherHolder!=null)
    	{
    		searcherHolder.partion=core.getName()+"@"+partion;
//        	log.info("ref create "+searcherHolder.toDebugMsg());
    		return searcherHolder.get();
    	}
    }
    
    if (searcherHolder==null) {
      searcherHolder = core.getSearcher("default",true,false,higohb);
    }

    return searcherHolder.get();
  }

  // The solr core (coordinator, etc) associated with this request
  public SolrCore getCore() {
    return core;
  }

  // The index schema associated with this request
  public IndexSchema getSchema() {
    //a request for a core admin will no have a core
    return core == null? null: core.getSchema();
  }

  /**
   * Frees resources associated with this request, this method <b>must</b>
   * be called when the object is no longer in use.
   */
  public void close() {
    this.decref();
  }
  
  private void decref()
  {
	  if (searcherHolder!=null) {
	      searcherHolder.decref();
//	      log.info("ref close "+searcherHolder.toDebugMsg());
	      searcherHolder = null;
	    }
  }

  /** A Collection of ContentStreams passed to the request
   */
  public Iterable<ContentStream> getContentStreams() {
    return streams; 
  }
  
  public void setContentStreams( Iterable<ContentStream> s ) {
    streams = s; 
  }

  public String getParamString() {
    return origParams.toString();
  }

  @Override
  public String toString() {
    return this.getClass().getSimpleName() + '{' + params + '}';
  }

}
